<template>
  <div :class="{'show':show}" class="header-search">
    <el-select
      ref="headerSearchSelect"
      v-model="search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="输入合约关键字"
      class="header-search-select"
      @change="change"
    >
      <el-option v-for="item in options" :key="item.code" :value="item" :label="item.fullname" />
    </el-select>
  </div>
</template>

<script>
// fuse is a lightweight fuzzy-search module
// make search results more in line with expectations
import Fuse from 'fuse.js'
import path from 'path'
import {getHost} from '@/utils/socket' // secondary package based on el-pagination

export default {
  name: 'HeaderSearch',
  data() {
    return {
      search: '铁矿石',
      options: [
      ],
      searchPool: [],
      show: true,
      fuse: undefined
    }
  },
  computed: {
    routes() {
      return this.$store.getters.permission_routes
    }
  },
  watch: {
    routes() {
      this.searchPool = this.generateRoutes(this.routes)
    },
    searchPool(list) {
      this.initFuse(list)
    },
    show(value) {
      if (value) {
        document.body.addEventListener('click', this.close)
      } else {
        document.body.removeEventListener('click', this.close)
      }
    }
  },
  mounted() {
    this.searchPool = this.generateRoutes(this.routes)
    this.init()

    let localSymbolList = window.localStorage.getItem('localSymbols')
    console.log('localSymbols >> ',localSymbolList,)
    if(typeof(localSymbols) == undefined){
      this.getList()
    }
    localSymbolList = JSON.parse(localSymbolList)
    this.options = localSymbolList

    let symbolData = window.localStorage.getItem('localSymbol')
    try {
      symbolData = JSON.parse(symbolData)
      this.search = symbolData.fullname
      console.log(symbolData)
      
    } catch (error) {
      
    }
  },
  methods: {
    init: function () {
      if(typeof(WebSocket) === "undefined"){
          alert("您的浏览器不支持socket")
      }else{
          // 实例化socket
          this.socket = new WebSocket(getHost())
          // 监听socket连接
          this.socket.onopen = this.open
          // 监听socket错误信息
          this.socket.onerror = this.error
          // 监听socket消息
          this.socket.onmessage = this.getMessage
      }
    },
    open: function () {

        this.connected = 'loaded'

        this.getList()
    },
    error: function (e) {
        console.log("连接错误",JSON.stringify(e))
    },
    getMessage: function (receiveData) {
      receiveData = JSON.parse(receiveData.data)
        console.log(receiveData)
      if(receiveData.status != 200){
          console.log(receiveData.msg)
      }else{
        window.localStorage.setItem('localSymbols',JSON.stringify(receiveData.data.list))
        this.list = receiveData.data.list
        this.total = receiveData.data.total
      }
        console.log(this.list)
    },
    send: function (params) {
      params = JSON.stringify(params)
      this.socket.send(params)
    },
    getList:function(){
      this.send({
        "conversationType":"quotation.subscribe.list",
        "message":{},
        "target":{"id":"3"}
      })
    },
    close: function () {
        console.log("socket已经关闭")
    },
    click() {
    },
    close() {
      this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
    },
    change(val) {
      console.log(val)
      window.localStorage.setItem("localSymbol",JSON.stringify(val))
      window.location.reload()
    },
    initFuse(list) {
      this.fuse = new Fuse(list, {
        shouldSort: true,
        threshold: 0.4,
        location: 0,
        distance: 100,
        maxPatternLength: 32,
        minMatchCharLength: 1,
        keys: [{
          name: 'title',
          weight: 0.7
        }, {
          name: 'path',
          weight: 0.3
        }]
      })
    },
    // Filter out the routes that can be displayed in the sidebar
    // And generate the internationalized title
    generateRoutes(routes, basePath = '/', prefixTitle = []) {
      let res = []

      for (const router of routes) {
        // skip hidden router
        if (router.hidden) { continue }

        const data = {
          path: path.resolve(basePath, router.path),
          title: [...prefixTitle]
        }

        if (router.meta && router.meta.title) {
          data.title = [...data.title, router.meta.title]

          if (router.redirect !== 'noRedirect') {
            // only push the routes with title
            // special case: need to exclude parent router without redirect
            res.push(data)
          }
        }

        // recursive child routes
        if (router.children) {
          const tempRoutes = this.generateRoutes(router.children, data.path, data.title)
          if (tempRoutes.length >= 1) {
            res = [...res, ...tempRoutes]
          }
        }
      }
      return res
    },
    querySearch(query) {
      if (query !== '') {
        this.options = this.fuse.search(query)
      } else {
        this.options = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;
  margin-right: 600px;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    /deep/ .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      background: #ededed;
      border-radius: 5px;
      padding:10px 20px;
      vertical-align: middle;
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
